package ca.etsmtl.log720.lab2.dao;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

/**
 * Gère la connection à la Database
 */
public class DBConnection {
	
	static DBConnection instance = new DBConnection();
	
	Connection dataSourceConnection;
	
	private DBConnection(){
		resetConnection();
		
	}
	
	/*
	 * Retourne l'unique instance de DBConnection
	 */
	public static DBConnection getInstance(){
		return instance;
	}
	
	/*
	 * Retourne la connection à la Database
	 */
	public Connection getConnection(){
		
		try {
			if(dataSourceConnection.isClosed())
				resetConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return dataSourceConnection;
	}
	
	/*
	 * Démarrer la connection avec la Database
	 */
	private void resetConnection(){
		Context namingContext;
		try {
			namingContext = new InitialContext();
			DataSource dataSource = (DataSource) namingContext.lookup ("java:comp/env/jdbc/equipe10-log720-A13-lab2");
			dataSourceConnection = dataSource.getConnection();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	

}
